<script setup lang="ts">
import { useRouter, useRoute } from "vue-router";
import type { Ref } from "vue";
import type { Router, RouteLocationNormalized } from "vue-router";
import type { UserInfo } from "@/types/userTypes/userTypes.ts";
import { ElMessage, ElMessageBox } from "element-plus";
import useUserStore from "@/pinia/modules/userStore/userStore.ts";
import useShopCartStore from "@/pinia/modules/shopCartStore/shopCartStore.ts";
import { storeToRefs } from "pinia";

const userStore = useUserStore();

const shopCartStore = useShopCartStore();

const router: Router = useRouter();

const route: RouteLocationNormalized = useRoute();

const { userInfo }: { userInfo: Ref<UserInfo> } = storeToRefs(userStore);


const handleLogout = async () => {
   const confirm: string = await ElMessageBox.confirm("确定退出登录吗?是否继续", "提示").catch(error => error);
   if (confirm === "cancel") return;
   const logoutResult: string = await userStore.logout();
   await shopCartStore.setShopCartList([]);
   await router.push({ path: "/login", query: { redirectUrl: route.fullPath } });
   ElMessage.success(logoutResult);
};

</script>

<template>
   <nav class="nav-bar">
      <ul class="container">
         <li v-if="userInfo.id"><a><i class="iconfont icon-user"></i>{{ userInfo.nickname }}</a></li>
         <li v-if="userInfo.id" @click="handleLogout"><a>退出登录</a></li>
         <li v-if="!userInfo.id">
            <RouterLink to="/login">请先登录</RouterLink>
         </li>
         <li><a>免费注册</a></li>
         <li><a>我的订单</a></li>
         <li><a>会员中心</a></li>
         <li><a>帮助中心</a></li>
         <li><a>关于我们</a></li>
         <li><a><i class="iconfont icon-phone"></i>手机版</a></li>
      </ul>
   </nav>
</template>

<style scoped lang="less">
.nav-bar {
   background: #333;

   ul {
      display: flex;
      height: 53px;
      justify-content: flex-end;
      align-items: center;

      li {
         a {
            padding: 0 15px;
            color: #cdcdcd;
            line-height: 1;
            display: inline-block;

            i {
               font-size: 14px;
               margin-right: 2px;
            }

            &:hover {
               color: @xtxColor;
            }
         }

         ~ li {
            a {
               border-left: 2px solid #666;
            }
         }
      }
   }
}
</style>
